const { get, put, upload } = require('../../utils/request');

Page({
  data: {
    postId: null,
    title: '',
    content: '',
    calories: '',
    images: [],
    isFormValid: false
  },

  onLoad(options) {
    if (options.id) {
      this.setData({ postId: options.id });
      this.loadPostData(options.id);
    }
  },

  async loadPostData(postId) {
    try {
      wx.showLoading({ title: '加载中...' });
      const res = await get(`/community/posts/${postId}`);
      
      if (res) {
        const { title, content, calories, images } = res;
        this.setData({
          title,
          content,
          calories: calories ? calories.toString() : '',
          images: images || []
        });
        this.checkFormValid();
      } else {
        throw new Error(res.message || '加载失败');
      }
    } catch (error) {
      console.error('加载帖子失败:', error);
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  onTitleInput(e) {
    this.setData({
      title: e.detail.value
    });
    this.checkFormValid();
  },

  onContentInput(e) {
    this.setData({
      content: e.detail.value
    });
    this.checkFormValid();
  },

  onCaloriesInput(e) {
    this.setData({
      calories: e.detail.value
    });
    this.checkFormValid();
  },

  async chooseImage() {
    try {
      const res = await wx.chooseMedia({
        count: 9 - this.data.images.length,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        sizeType: ['compressed']
      });

      wx.showLoading({ title: '上传中...' });
      
      const uploadTasks = res.tempFiles.map(file => this.uploadImage(file.tempFilePath));
      const uploadedImages = await Promise.all(uploadTasks);
      
      this.setData({
        images: [...this.data.images, ...uploadedImages]
      });
    } catch (error) {
      console.error('选择图片失败:', error);
      wx.showToast({
        title: '选择图片失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  async uploadImage(tempFilePath) {
    try {
      const res = await upload('/upload/image', tempFilePath);
      if (res.code === 0) {
        return res.url;
      }
      throw new Error('上传失败');
    } catch (error) {
      console.error('上传图片失败:', error);
      throw error;
    }
  },

  deleteImage(e) {
    const index = e.currentTarget.dataset.index;
    const images = [...this.data.images];
    images.splice(index, 1);
    this.setData({ images });
  },

  checkFormValid() {
    const isFormValid = this.data.title.trim() && this.data.content.trim();
    this.setData({ isFormValid });
  },

  async handleSubmit() {
    if (!this.data.isFormValid) return;

    try {
      wx.showLoading({ title: '保存中...' });
      
      const postData = {
        title: this.data.title.trim(),
        content: this.data.content.trim(),
        calories: this.data.calories ? parseFloat(this.data.calories) : 0,
        images: this.data.images
      };

      const res = await put(`/community/posts/${this.data.postId}`, postData);
      
      if (res.code === 0) {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
        
        // 返回上一页并刷新
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2];
        if (prevPage) {
          prevPage.loadPosts();
        }
        
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        throw new Error(res.message || '保存失败');
      }
    } catch (error) {
      console.error('保存失败:', error);
      wx.showToast({
        title: error.message || '保存失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  }
}); 